const BASE_URL = 'http://shalu-fixedassetsmanagement-admin-dev.shalu.com'
// const BASE_URL = "http://127.0.0.1"
// const BASE_URL = "http://10.0.0.200"
// 获取 token
function getToken() {
	return uni.getStorageSync('token') || ''
}

function request({ url, method = 'GET', data = {}, header = {} }) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + url,
			method,
			data,
			header: {
				'Accept': 'application/json;charset=utf-8',
				'Content-Type': header['Content-Type'] || 'application/json;charset=utf-8',
				withCredentials: true,
				dataType: 'json',
				'Authorization': getToken(),
				...header
			},
			success: res => {
				const { statusCode, data } = res
				if (statusCode === 200) {
					resolve(data)
				} else if (statusCode === 202) {
					resolve({ statusCode, data })
				} else {
					uni.showToast({
						title: data.message || '请求失败，请重新登录',
						icon: 'none'
					})
					uni.removeStorageSync('token');
					uni.removeStorageSync('userInfo');
					uni.reLaunch({
						url: '/pages/login/login'
					})
					reject(data)
				}
			},
			fail: err => {
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
}

// 新增 upload 方法
function upload({ url, filePath, name = 'file', formData = {}, header = {} }) {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: BASE_URL + url,
			filePath,
			name,
			formData,
			header: {
				'Authorization': getToken(),
				...header
			},
			success: res => {
				try {
					const data = JSON.parse(res.data)
					if (data.code) {
						resolve(data)
					} else {
						uni.showToast({
							title: data.message || '上传失败',
							icon: 'none'
						})
						reject(data)
					}
				} catch (e) {
					uni.showToast({ title: '返回格式错误', icon: 'none' })
					reject(e)
				}
			},
			fail: err => {
				uni.showToast({ title: '上传失败', icon: 'none' })
				reject(err)
			}
		})
	})
}

// 导出 BASE_URL
export { BASE_URL }

// 快捷方法封装
export default {
	get(url, data = {}, header = {}) {
		return request({ url, method: 'GET', data, header })
	},
	post(url, data = {}, header = {}) {
		return request({ url, method: 'POST', data, header })
	},
	put(url, data = {}, header = {}) {
		return request({ url, method: 'PUT', data, header })
	},
	delete(url, data = {}, header = {}) {
		return request({ url, method: 'DELETE', data, header })
	},
	request, // 如果需要自定义 method，也可以直接用这个
	upload,
	getToken
}
